﻿using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using FlightSearchServer.TicketSellingService;

namespace FlightSearchServer
{
    [ServiceContract]
    public interface IFlightSearchRegService
    {
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "sellers/{id}")]
        void Register(string id, string uri);

        [OperationContract]
        [WebInvoke(Method = "DELETE", UriTemplate = "sellers/{id}")]
        void Unregister(string id);
    }

    public class FlightSearchRegService : IFlightSearchRegService
    {
        public void Register(string id, string uri)
        {
            if (WebOperationContext.Current != null)
            {
                try
                {
                    var cf = new ChannelFactory<ITicketSellingService>(new BasicHttpBinding(), uri);
                    ITicketSellingService channel = cf.CreateChannel();

                    TicketSellersDatabase.Remove(id); // dispose old channel if exists
                    TicketSellersDatabase.Add(id, channel);
                }
                catch (Exception e)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    WebOperationContext.Current.OutgoingResponse.StatusDescription = e.Message;
                }
            }
        }

        public void Unregister(string id)
        {
            if (WebOperationContext.Current != null)
            {
                TicketSellersDatabase.Remove(id);
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
            }
        }
    }
}
